﻿$scriptPath = "C:\scripts\runRandomBing.ps1"
$taskName = "BingSearchScheduler"

# 创建任务动作
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass -File `"$scriptPath`""

# 创建两个触发器：
# 1. 每天凌晨1点
$dailyTrigger = New-ScheduledTaskTrigger -Daily -At 1am
# 2. 开机时触发（延迟2分钟执行，避免系统启动时资源紧张）
$startupTrigger = New-ScheduledTaskTrigger -AtStartup
$startupTrigger.Delay = "PT2M"  # 延迟2分钟

# 设置任务运行权限
$principal = New-ScheduledTaskPrincipal -UserId "$env:USERNAME" -LogonType S4U -RunLevel Highest

# 如果任务存在，先删除
if (Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue) {
    Unregister-ScheduledTask -TaskName $taskName -Confirm:$false
}

# 注册任务（同时使用两个触发器）
Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $dailyTrigger, $startupTrigger -Principal $principal

Write-Host "✅ 计划任务 [$taskName] 已创建：" -ForegroundColor Green
Write-Host "   - 每天凌晨1点执行" -ForegroundColor Green
Write-Host "   - 系统启动后2分钟执行" -ForegroundColor Green
Write-Host "   - 执行脚本: $scriptPath" -ForegroundColor Green